package com.longtop.framework.sys.file.supports;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SmartDowload {
	private Log log = LogFactory.getLog(SmartDowload.class);
	protected HttpServletResponse m_response;
	private String m_contentDisposition;

	public SmartDowload(HttpServletResponse httpservletresponse) {
		this.m_response = httpservletresponse;
	}

	public void downloadFile(String s, boolean isContextPath) throws ServletException, IOException {
		downloadFile(s, null, null, isContextPath);
	}

	public void downloadFile(String s, String s1, boolean isContextPath) throws ServletException, IOException {
		downloadFile(s, s1, null, isContextPath);
	}

	public String getRealPath(String s) {
		String sPath = "";
		FileControl fileControl = new FileControl(s);
		sPath = fileControl.getMyFile().getAbsolutePath();
		return sPath;
	}

	public void downloadFile(String s, String s1, String s2, boolean isContextPath) throws ServletException, IOException {
		downloadFile(s, s1, s2, 65000, isContextPath);
	}

	public void downloadFile(String path, String contentType, String fileName, int readSize, boolean isContextPath) throws ServletException, IOException {
		String sPath = path;
		if (path == null)
			throw new IllegalArgumentException("File '" + path + "' not found (1040).");
		if (path.equals(""))
			throw new IllegalArgumentException("File '" + path + "' not found (1040).");
		if (isContextPath) {
			sPath = getRealPath(path);
		}

		java.io.File file = new java.io.File(sPath);
		FileInputStream fileinputstream = new FileInputStream(file);
		long filelength = file.length();
		int k = 0;
		byte[] abyte0 = new byte[readSize];
		if (contentType == null) {
			this.m_response.setContentType("application/x-msdownload");
		} else if (contentType.length() == 0)
			this.m_response.setContentType("application/x-msdownload");
		else
			this.m_response.setContentType(contentType);
		this.m_response.setContentLength((int) filelength);
		this.m_contentDisposition = "attachment;";
		if (fileName == null) {
			this.m_response.setHeader("Content-Disposition", this.m_contentDisposition + " filename=" + toUtf8String(getFileName(sPath)));
		} else if (fileName.length() == 0) {
			this.m_response.setHeader("Content-Disposition", this.m_contentDisposition);
		} else {
			this.m_response.setHeader("Content-Disposition", this.m_contentDisposition + " filename=" + toUtf8String(fileName));
		}

		while (k < filelength) {
			int len = fileinputstream.read(abyte0, 0, readSize);
			k += len;
			this.m_response.getOutputStream().write(abyte0, 0, len);
		}
		fileinputstream.close();

		// int size=readSize;
		// byte[] b=new byte[size];
		// int len=0;
		// while((len=fileinputstream.read(b, 0, size))!=-1){
		// m_response.getOutputStream().write(b,0,len);
		// m_response.getOutputStream().flush();
		// }
	}

	public String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); ++i) {
			char c = s.charAt(i);
			if ((c >= 0) && (c <= 255)) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					b = new byte[0];
				}
				for (int j = 0; j < b.length; ++j) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	private String getFileName(String s) {
		int i = 0;
		i = s.lastIndexOf(47);
		if (i != -1)
			return s.substring(i + 1, s.length());
		i = s.lastIndexOf(92);
		if (i != -1)
			return s.substring(i + 1, s.length());

		return s;
	}

}